<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<App />
		</div>
		<script src="../node_modules/vue/dist/vue.js"></script>
		<script src="../node_modules/axios/dist/axios.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			let App = {
				template:`
				<div>
					<span v-show="isShow">loading....</span>
					<button @click="sendAllAjax">点击发送并发请求</button>
				</div>
				`,
				data(){
					return {
						isShow: false 
					}
				},
				methods: {
					sendAjax1(){
						let param = {
							params: {
								name: '111',
								age: 111,
							}
						}
						return this.$axios.get('getData.json', param)
					},
					sendAjax2(){
						let param = {
							params: {
								name: '222',
								age: 333,
							}
						}
						return this.$axios.get('getData2.json', param)
					},
					sendAllAjax(){
						this.$axios.all([this.sendAjax1(),this.sendAjax2()]).then(this.$axios.spread((res1, res2)=>{
							//console.log(res1, res2)
						})).catch(err => {
							//其中一个失败则进入err分支
						})
					},
					
				}
			}
			
			//挂载axios
			Vue.prototype.$axios = axios
			
			let loading;
			// 全局添加请求拦截器,模拟cookie
			axios.interceptors.request.use(config => {
				//在发送请求前操作
				//引入Elementui的loading组件实现加载效果
				/*loading = Loading.service({
				    lock: true,
				    text: '拼命加载中...',
				    background:'rgba(255,255,255,0)',
			  	})*/
				let token = sessionStorage.getItem('token')
				if(token){
					config.headers['token'] = token
				}
				console.log(config)
				return config
			}, err=>{
				//对请求错误操作
				return Promise.reject(err)
			})
			
			// 全局添加响应拦截器
			axios.interceptors.response.use(response => {
				//对响应数据操作
				//关闭加载效果
				//loading.close()
				if(response.data.token){
					sessionStorage.setItem('token', response.data.token)
				}
				console.log(response)
				return response
			}, err=>{
				//对响应错误操作
				return Promise.reject(err)
			})
			
			let vm = new Vue({
				el: '#app',
				components: {App},
				data(){
					return {
					}
				},
			})
		</script>
	</body>
</html>
